#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <malloc.h>

#define thread_num 16
#define MB (1024 * 1024)

int *array;
int length; // array length
int count = 0;
int t;      // number of threads

void *count3s_thread(void* id);

pthread_mutex_t m;

int main()
{
    pthread_mutex_init(&m, NULL);
    int i;
    int tid[thread_num];
    pthread_t threads[thread_num];

    length = 64 * MB; // 256MB
    array = malloc(length * sizeof(int));
    
    for (i = 0; i < length; i++)
        array[i] = i % 2 ? 4 : 3; // 偶数 i 对应数值 3

    for (t = 0; t < thread_num; t++) // 循环创建 16 个线程
    {
        // count = 0;
        tid[t] = t;
        int err = pthread_create(&(threads[t]), NULL, count3s_thread, &(tid[t]));
        if (err)
        {
            printf("create thread error!\n");
            return 0;
        }
    }

    for (t = 1; t < thread_num; t++) // 等待前面创建的计数线程结束
        pthread_join(threads[t], NULL);

    printf("Total count= %d \n", count);
    return 0;
}

void *count3s_thread(void* id)
{
    int *thread_id = (int*)id;
    int start = (*thread_id) * (length / thread_num); // 每个线程的起始位置
    int end = start + (length / thread_num); // 每个线程的结束位置

    for (int i = start; i < end; i++)
    {
        if (array[i] == 3)
        {
            pthread_mutex_lock(&m);
            count++; // 计数
            pthread_mutex_unlock(&m);
        }
    }

    return NULL;
}